#! python3
# -*- coding: UTF-8 -*-
# @Time    : 2025/5/26 12:22
# @Author  : AndrewWay
# @version : 1.0
# @notes   ：
import datetime
import random
import time

import pyautogui
import pyperclip

from common.monitor import WeChatMonitor

from scripts.wechat.base import Base


class GetWeChatMsg(Base):
    def __init__(self):
        super().__init__()

    # 获取
    def get_msg(self, keyword_list, group):
        self.slide_screen()
        self.logger.info("初始化聊天内容完成,准备识别关键词")
        # 获取聊天框所有消息
        chat_window = self.auto.WindowControl(ClassName="ChatWnd", Name=f"{group}")
        all_msg = chat_window.ListControl(Name="消息").GetChildren()
        for keyword in keyword_list:
            for item in all_msg:
                word = item.Name
                if keyword in word:
                    # 发送者
                    sender_name = None
                    try:
                        sender_name = item.GetChildren()[0].GetChildren()[1].GetChildren()[0].GetChildren()[0].Name
                    except Exception as e:
                        self.logger.error(f'这不是有效的消息，错误原因：{e}')
                    if sender_name:
                        print(word)
                        print(sender_name)
                        msg = f'监控触发关键词的群主消息\n\n群名：{group}\n\n关键词："【{keyword}】"\n\n出现在："【{word}】"\n\n发送者是：【{sender_name}】'
                        WeChatMonitor(msg).start()
                    else:
                        self.logger.info('不是有效的消息，不发送预警提示')

    def open_chat_wnd_and_get_msg(self, item, group_name, keyword_list):
        """
        :param keyword_list:
        :param item: 获取发言的目标用户
        :param group_name: 群聊名称
        :return:
        """
        if group_name is not None:
            chat_group = self.auto.WindowControl(searchDepth=30, Name=f'{group_name}')
        if group_name is not None and chat_group.Exists(maxSearchSeconds=3) and isinstance(item, dict):
            """
            检测到这个聊天窗口已经打开，直接设置为当前活动的窗口并最大化
            """
            chat_group.SetActive()
            chat_group.Maximize()
            if keyword_list is None:
                self.get_all_msg(item, group_name)
            elif keyword_list is not None:
                self.get_user_keyword(item, group_name, keyword_list)
        else:
            """
            检测到这个聊天窗口没有打开，需要自动打开这个群聊
            """
            if group_name is not None:
                self.open_chat_window(group_name)
                # 初始化聊天消息
                self.slide_screen()
            if keyword_list is None and isinstance(item, dict):
                self.get_all_msg(item, group_name)
            elif keyword_list is not None:
                self.get_user_keyword(item, group_name, keyword_list)
            # 检测指定好友的聊天
            elif group_name is None and keyword_list is None and isinstance(item, str):
                user_chat = self.auto.WindowControl(searchDepth=30, Name=f"{item}")
                # self.open_chat_window(item)
                # 初始化聊天消息
                # self.slide_screen()
                if user_chat.Exists(maxSearchSeconds=3) and isinstance(item, str):
                    user_chat.SetActive()
                    user_chat.Maximize()
                    self.get_target_user_msg(item)
                else:
                    self.open_chat_window(item)
                    self.slide_screen()
                    self.get_target_user_msg(item)

    def get_target_user_msg(self, item):
        """
        :param item: 好友名称
        :return:
        """
        self.logger.info(f'初始化聊天内容完成，准备获取好友{item}的消息')
        exist_msg = self.get_exist_msg(3, friend_name=item)
        chat_window = self.auto.WindowControl(ClassName="ChatWnd", Name=f"{item}")
        user_msg_list = chat_window.ListControl(Name="消息").GetChildren()
        for msg in user_msg_list:
            data_dict = {}
            # 好友的消息
            word = msg.Name
            sender_name = None
            try:
                sender_name = msg.GetChildren()[0].GetChildren()[0].Name
            except Exception as e:
                self.logger.warning(f'这不是有效的消息，错误原因：{e}')
            if sender_name and sender_name in item:
                if word in [el[0] for el in exist_msg]:
                    self.logger.info(f'【{word}】已经获取过，跳过')
                    continue
                else:
                    self.logger.info(f"{sender_name} : {word}")
                    monitor_msg = f"监控指定好友的消息\n\n好友：【{item}】\n\n消息：【{word}】"
                    WeChatMonitor(monitor_msg).start()
                    if word not in ['[图片]', '[视频]', '[链接]', '[聊天记录]']:
                        if len(word) > 256:
                            word = word[:255]
                        data_dict["msg_content"] = word
                        data_dict["friend_name"] = sender_name
                        data_dict["task_type"] = 3
                        self.insert_msg(data_dict)
                        time.sleep(random.uniform(1.5, 1.9))
            else:
                self.logger.info('不是目标消息，不发送预警提示')

    def get_user_keyword(self, item, group_name, keyword_list):
        """

        :param item: 获取发言的目标用户
        :param keyword_list: 关键词列表
        :param group_name: 群聊名称,群聊2
        :return:
        """
        self.logger.info('初始化聊天内容完成，准备获取触发关键词的群主发言')
        exist_msg = self.get_exist_msg(2, friend_name=None)
        chat_window = self.auto.WindowControl(ClassName="ChatWnd", Name=group_name)
        keyword_msg = chat_window.ListControl(Name="消息").GetChildren()
        for msg in keyword_msg:
            data_dict = {}
            # 单条群聊消息
            word = msg.Name
            if word in [el[0] for el in exist_msg]:
                self.logger.info(f'{word}已经获取过，跳过')
                continue
            sender_name = None
            try:
                sender_name = msg.GetChildren()[0].GetChildren()[1].GetChildren()[0].GetChildren()[0].Name
            except Exception as e:
                self.logger.warning(f'这不是有效的消息，错误原因：{e}')
                continue
            if sender_name and sender_name == item.get(group_name):
                for keyword in keyword_list:
                    if keyword in word:
                        self.logger.info(f"{sender_name} : {word}")
                        monitor_msg = f"群名：【{group_name}】\n\n群主：【{sender_name}】\n\n消息：【{word}】\n\n触发关键词：【{keyword}】"
                        WeChatMonitor(monitor_msg).start()
                        if word not in ['[图片]', '[视频]', '[链接]', '[聊天记录]']:
                            if len(word) > 256:
                                word = word[:250]
                            data_dict['keyword'] = keyword
                            data_dict["msg_content"] = word
                            data_dict["sender_name"] = sender_name
                            data_dict["group_name"] = group_name
                            data_dict["task_type"] = 2
                            self.insert_msg(data_dict)

                            time.sleep(random.uniform(1.3, 1.6))
            else:
                self.logger.info('不是目标消息，不发送预警提示')

    def get_all_msg(self, item, group_name):
        """
        获取群主所有的发言
        :param item: 群主1
        :param group_name:群聊名称
        :return:
        """
        exist_msg = self.get_exist_msg(1, friend_name=None)
        self.logger.info('初始化聊天内容完成，准备获取群主所有的聊天消息')
        chat_window = self.auto.WindowControl(ClassName="ChatWnd", Name=group_name)
        # 获取群主所有的发言
        all_msg = chat_window.ListControl(Name="消息").GetChildren()
        for msg in all_msg:
            data_dict = {}
            # 单条群聊消息
            word = msg.Name
            if word in [el[0] for el in exist_msg]:
                self.logger.info(f'{word}已经获取过，跳过')
                continue
            else:
                sender_name = None
                try:
                    sender_name = msg.GetChildren()[0].GetChildren()[1].GetChildren()[0].GetChildren()[0].Name
                except Exception as e:
                    self.logger.warning(f'这不是有效的消息，错误原因：{e}')
                if sender_name and sender_name == item.get(group_name):
                    self.logger.info(f"{sender_name} : {word}")
                    monitor_msg = f"监控群主的所有消息\n\n群名：【{group_name}】\n\n群主：【{sender_name}】\n\n消息：【{word}】"
                    WeChatMonitor(monitor_msg).start()
                    if word not in ['[图片]', '[视频]', '[链接]', '[聊天记录]']:
                        if len(word) > 256:
                            word = word[:250]
                        # 赋值给字典
                        data_dict["msg_content"] = word
                        data_dict["sender_name"] = sender_name
                        data_dict["task_type"] = 1
                        data_dict["group_name"] = group_name
                        self.insert_msg(data_dict)
                        time.sleep(random.uniform(1.5, 1.9))
                else:
                    self.logger.info('不是目标消息，不发送预警提示')

    # 从数据库中获取已经存在的消息
    def get_exist_msg(self, task_type, friend_name):
        """从数据库获取指定类型的微信历史消息

        Args:
            task_type: 任务类型(1/2/其他)

        Returns:
            消息内容列表
        """
        if task_type != 3:
            sql = f"SELECT msg_content FROM `wechat_msg` WHERE task_type=%s AND create_time>=CURRENT_DATE()"
            result = self.db.query(sql, task_type)
            return result
        else:
            sql = "SELECT msg_content FROM `wechat_msg` WHERE task_type=%s AND friend_name=%s AND create_time>=CURRENT_DATE()"
            return self.db.query(sql, [task_type, friend_name])

    def insert_msg(self, data_dict):
        create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        data_dict["create_time"] = create_time
        keys = ", ".join(f"`{key}`" for key in data_dict.keys())
        values_placeholder = ", ".join(["%s"] * len(data_dict))
        sql = f"INSERT INTO `wechat_msg` ({keys}) VALUES ({values_placeholder})"
        self.db.exec_one(sql, list(data_dict.values()))
        self.logger.info('消息保存成功')


if __name__ == '__main__':
    get = GetWeChatMsg()
    get.get_exist_msg(1)
